<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2021/3/25
  Time: 17:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>信息管理主页</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/layui/css/layui.css">
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
    <jsp:include page="../../common/header.jsp"></jsp:include>
    <jsp:include page="../../common/side.jsp"></jsp:include>

    <div class="layui-body">
        <!-- 内容主体区域 -->
        <div style="padding: 15px;">
            <fieldset class="layui-elem-field site-demo-button" style="margin-top: 30px;padding: 10px">
                <legend>职员信息管理</legend>
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md1 layui-col-xs12"><label class="layui-form-label">搜索姓名：</label></div>
                    <div class="layui-col-md3 layui-col-xs12"><input class="layui-input" name="empName" id="empName"
                                                                     autocomplete="off"></div>
                    <div class="layui-col-md1 layui-col-xs12"><label class="layui-form-label">时间范围：</label></div>
                    <div class="layui-col-md3 layui-col-xs12"><input type="text" class="layui-input" name="dateRange"
                                                                     id="dateRange" placeholder="请选择时间范围"></div>
                    <div class="layui-col-md2 layui-col-xs12">
                        <button class="layui-btn" data-type="reload" id="searchBtn">搜索</button>
                        <i id="searInfo" class="layui-icon layui-icon-about"
                           style="font-size: 20px; color: #888f92;"></i></div>
                </div>
                </form>
            </fieldset>

            <table class="layui-hide" id="empTb" lay-filter="empTb"></table>

            <script type="text/html" id="toolbar">
                <div class="layui-btn-container">
                    <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
                    <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
                    <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
                    <button class="layui-btn layui-btn-sm" lay-event="addEmp">添加成员</button>
                </div>
            </script>

            <script type="text/html" id="barDemo">
                <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
            </script>

            <script type="text/html" id="dateTransTpl">
                <span style="color: #045751;font-weight: bolder" class="layui-icon layui-icon-log">
                    {{d.joinDateStr}}
                </span>
            </script>
            <script type="text/html" id="addressTpl">
                <span style="color: #16843c;" class="layui-icon layui-icon-flag">
                    {{d.address}}
                </span>
            </script>
            <script type="text/html" id="salaryTpl">
                <label style="color: #ba0b1d;font-family: 'Comic Sans MS'">
                    ￥{{d.salary}}
                </label>
            </script>
            <script type="text/html" id="genderTpl">
                {{#  if(d.gender === '女'){ }}
                <span style="color: #F581B1;" class="layui-icon layui-icon-female">{{ d.gender }}</span>
                {{#  } else { }}
                <span style="color: #7abbec;" class="layui-icon layui-icon-male">{{ d.gender }}</span>
                {{#  } }}
            </script>
        </div>
    </div>

    <jsp:include page="../../common/footer.jsp"></jsp:include>
</div>
<script src="${pageContext.request.contextPath}/static/layui/layui.js"></script>
<script>
    //JavaScript代码区域
    layui.use(['table', 'laydate', 'layer', 'jquery'], function () {
        var table = layui.table;
        var laydate = layui.laydate;
        var layer = layui.layer;
        var $ = layui.jquery;

        // 为#empName添加提示框
        tipsMsg($, layer, "#empName", "按姓名查询: %?%", "#123456");
        // 为#dateRange添加提示框
        tipsMsg($, layer, "#dateRange", '按时间范围:<br/>例如：2020-01-01 ~ 2021-01-01', "#123456");
        // 为#searInfo添加提示框
        tipsMsg($, layer, "#searInfo", '模糊查询:<br/>根据姓名或者时间范围查询', "#123456");

        //执行一个laydate实例
        laydate.render({
            elem: '#dateRange' //指定元素
            , range: '~'
            , done: function (value, date, endDate) {
                // done--时间选择完的回调方法
                //console.log(value); //得到日期生成的值，如：2017-08-18
                //console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                //console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
            }
        });

        table.render({
            elem: '#empTb'
            , id: "empTb"
            , url: '${pageContext.request.contextPath}/emp/empList'
            , toolbar: '#toolbar' //开启头部工具栏，并为其绑定左侧模板
            , defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                title: '提示'
                , layEvent: 'LAYTABLE_TIPS'
                , icon: 'layui-icon-tips'
            }]
            , title: '用户数据表'
            , skin: 'col'
            , even: true
            , cols: [[
                {type: 'checkbox', fixed: 'left'}
                , {field: 'id', title: 'ID', width: 80, fixed: 'left', unresize: true, sort: true, align: "center"}
                , {field: 'firstName', title: '姓氏', width: 140, edit: 'text', align: "center"}
                , {field: 'lastName', title: '尾名', width: 140, edit: 'text', align: "center"}
                , {
                    field: 'gender',
                    title: '性别',
                    width: 80,
                    edit: 'text',
                    sort: true,
                    templet: "#genderTpl",
                    align: "center"
                }
                , {field: 'age', title: '年龄', width: 80, sort: true, edit: "text"}
                , {
                    field: 'salary',
                    title: '薪资',
                    width: 120,
                    sort: true,
                    edit: "text",
                    templet: "#salaryTpl",
                    align: "center"
                }
                , {field: 'address', title: '城市', edit: "text", templet: "#addressTpl", align: "center"}
                , {field: 'joinDateStr', title: '加入时间', templet: '#dateTransTpl', edit: "text", align: "center"}
                , {field: 'id', title: '归属部门ID', align: "center", templet: '<span>{{d.dept.id}}</span>', hide: true}
                , {field: 'name', title: '归属部门', align: "center", templet: '<span>{{d.dept.name}}</span>'}
                , {field: 'joinDate', title: '加入时间戳', edit: "text", align: "center", hide: true}
                , {fixed: 'right', title: '操作', toolbar: '#barDemo', align: "center"}
            ]]
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 5 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页
                , limits: [1, 2, 5, 10, 20] //设置页容量选项
                , limit: 5 // 设置默认页容量
            }
            , response: {
                statusCode: 0 //重新规定成功的状态码为 200，table 组件默认为 0
            }
        });
        // 单元格编辑事件
        table.on('edit(empTb)', function (obj) {
            // console.log(obj);
            var value = obj.value //得到修改后的值
                , data = obj.data //得到所在行所有键值
                , field = obj.field; //得到字段
            //layer.msg('[ID: '+ data.id +'] ' + field + ' 字段更改为：'+ value);
            //将修改信息发送到数据后台
            // 由于前台已将将日期类型的属性转成了时间戳，传回后台时要封装成Date类型
            data.joinDate = new Date(data.joinDate);
            // 使用json格式传入后台
            myAjax($, JSON.stringify(data), '${pageContext.request.contextPath}/emp/update', "application/json", '')
            rbReload($, table);
        });
        //头工具栏事件
        table.on('toolbar(empTb)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'getCheckData':
                    var data = checkStatus.data;
                    layer.alert(JSON.stringify(data));
                    break;
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：' + data.length + ' 个');
                    break;
                case 'isAll':
                    layer.msg(checkStatus.isAll ? '全选' : '未全选');
                    break;
                case "addEmp":
                    // 打开窗口用于添加成员
                    layer.open({
                        type: 2 //此处以iframe举例
                        , title: '添加成员'
                        , area: ['722px', '700px']
                        , shade: 0.8
                        , maxmin: false
                        , offset: [ //为了演示，随机坐标
                            ($(window).height() - 722) / 2
                            , ($(window).width() - 700) / 2
                        ]
                        , content: '${pageContext.request.contextPath}/emp/addEmpform'
                        , btn: ['立即添加', '取消并关闭'] //只是为了演示
                        , no: function () {
                            layer.closeAll();
                        }
                        , btn1: function (index, layero) {
                            let body = layer.getChildFrame('body', index);
                            let data = {};
                            body.find("#addform").serializeArray().forEach(function (item) {    //获取弹出层写下的数据，input，下拉框啊，之类的表单元素（即changefileform下的所有数据）
                                data[item.name] = item.value;   //根据表单元素的name属性来获取数据
                            });
                            console.log(data);
                            layer.close(index);
                            layer.confirm("确定要添加吗?", {
                                time: 10000, //10s后自动关闭
                                btn: ['确认', '取消'],
                                icon: 0,
                                yes: function (index, layero) {
                                    //按钮【'确认'】的回调
                                    layer.close(index);
                                    myAjax($, data,
                                        '${pageContext.request.contextPath}/emp/insert', "application/x-www-form-urlencoded", "")
                                    rbReload($, table);
                                }
                                , btn2: function (index, layero) {
                                    layer.close(index);
                                }
                            });
                        }
                        , zIndex: layer.zIndex //重点1
                        , success: function (layero) {
                            layer.setTop(layero); //重点2
                        }
                    });
                    break;
                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
            }
            ;
        });

        //监听行工具事件
        table.on('tool(empTb)', function (obj) {
            var data = obj.data;
            console.log(data)
            if (obj.event === 'del') {
                layer.confirm('真的要删除' + data.firstName + data.lastName + '么？', {icon: 0}, function (index) {
                    data.joinDate = new Date(data.joinDate);
                    myAjax($, JSON.stringify(data), '${pageContext.request.contextPath}/emp/delete', "application/json", '');
                    rbReload($, table);
                    layer.close(index);
                });
            } else if (obj.event === 'edit') {
                layer.open({
                    type: 2 //此处以iframe举例
                    , title: '请编辑' + obj.data.firstName + obj.data.lastName + '的成员信息'
                    , area: ['722px', '700px']
                    , shade: 0.8
                    , maxmin: false
                    , offset: [ //为了演示，随机坐标
                        ($(window).height() - 722) / 2
                        , ($(window).width() - 700) / 2
                    ]
                    , content: '${pageContext.request.contextPath}/emp/eform?id=' + obj.data.id
                    , btn: ['提交数据', '取消并关闭'] //只是为了演示
                    , no: function () {
                        layer.closeAll();
                    }
                    , btn1: function (index, layero) {
                        let body = layer.getChildFrame('body', index);
                        let data = {};
                        body.find("#eform").serializeArray().forEach(function (item) {    //获取弹出层写下的数据，input，下拉框啊，之类的表单元素（即changefileform下的所有数据）
                            data[item.name] = item.value;   //根据表单元素的name属性来获取数据
                        });
                        layer.close(index);
                        layer.confirm("确定要修改吗?", {
                            time: 10000, //10s后自动关闭
                            btn: ['确认', '取消'],
                            icon: 0,
                            yes: function (index, layero) {
                                //按钮【'确认'】的回调
                                layer.close(index);
                                console.log(data)
                                myAjax($, JSON.stringify(data),
                                    '${pageContext.request.contextPath}/emp/update', "application/json", "")
                                rbReload($, table);
                            }
                            , btn2: function (index, layero) {
                                layer.close(index);
                            }
                        });
                    }
                    , zIndex: layer.zIndex //重点1
                    , success: function (layero) {
                        layer.setTop(layero); //重点2
                    }
                });
            }
        });
        // 模糊查询
        $("#searchBtn").click(() => {
            //console.log($("#empName").val(),$("#dateRange").val());
            // 封装json串准备发送给后台
            let search = {empName: $("#empName").val(), dateRange: $("#dateRange").val()}
            console.log(search);
            rbReload($, table)

        })
    });

    function rbReload($, table) {
        table.reload('empTb', {
            url: '${pageContext.request.contextPath}/emp/search'
            , where: {
                empName: $("#empName").val(),
                dateRange: $("#dateRange").val()
            }
        });
    }

    function tipsMsg($, layer, id, msg, color) {
        var tip;
        $(id).hover(function () {
            tip = layer.tips(msg, id, {tips: [1, color], time: 5000});
        }, function () {
            layer.close(tip);
        })
    }

    function myAjax($, myData, url, cType, sucsUrl) {
        $.ajax({
            url: url,
            data: myData,
            dataType: 'json',
            type: 'post',
            contentType: cType,
            success: function (data) {
                if (data.code === 1) {
                    layer.msg(data.message, {icon: 1});
                    if (sucsUrl !== "") {
                        setTimeout(() => {
                            location.href = sucsUrl;
                        }, 500)
                    }
                } else {
                    layer.msg(data.message, {icon: 5});
                    flag = false;
                }
            }
        })
    }
</script>
</body>
</html>
